package com.lcn.core.service.callback;

import com.lcn.comm.domain.CallbackInfo;
import com.lcn.comm.framework.task.TaskGroup;
import com.lcn.comm.framework.task.TaskGroupManager;
import com.lcn.comm.service.callback.CallbackService;
import com.weibo.api.motan.config.springsupport.annotation.MotanService;
import com.weibo.api.motan.util.LoggerUtil;

/**
 * <p>类说明</p>
 *
 * @author 张峰 zfvip_it@163.com
 * @create: 2017－12－24 上午11:11
 */
@MotanService
public class CallbackServiceImpl implements CallbackService {

    /**
     * 回调客户端
     *
     * @param callbackInfo
     * @return
     */
    public String callback(CallbackInfo callbackInfo) {
        TaskGroup taskGroup = TaskGroupManager.getInstance().getTaskGroup(callbackInfo.getGroupId());
        if (taskGroup != null) {
            LoggerUtil.info("需要通知提交的数据,groupId[{}]", taskGroup.getGroupId());
            if (taskGroup.isAwait()) {//已经等待
                return notifyWaitTask(taskGroup, callbackInfo.getState());
            } else {//继续等待
                int index = 0;
                while (true) {
                    if (index > 500) {
                        return "0";
                    }
                    if (taskGroup.isAwait()) {//已经等待
                        return notifyWaitTask(taskGroup, callbackInfo.getState());
                    }
                    index++;
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        } else {
            return "0";
        }
    }

    /**
     * 通知等待的task进行提交
     *
     * @param taskGroup
     * @param state
     * @return
     */
    private String notifyWaitTask(TaskGroup taskGroup, int state) {
        taskGroup.setState(state);
        //唤醒所有等待的task
        taskGroup.signalTask();
        while (true) {
            if (taskGroup.getTaskMap() == null || taskGroup.getTaskMap().isEmpty() || taskGroup.isRemove()) {//已经全部通知了
                return "1";
            }
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
